package com.greyshark.sanotrive.splash

import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.api.ApiConstant.PRIVACY_POLICY_SERVER
import com.common.app.data.api.ApiConstant.SERVICE_AGREEMENT_SERVER
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.dialog.PrivacyPolicyDialog
import com.common.app.helper.LaunchHelper
import com.common.app.helper.UserHelper
import com.common.base.app.extras.*
import com.common.base.utils.*
import com.greyshark.sanotrive.R
import com.greyshark.sanotrive.app.QXApplication
import com.greyshark.sanotrive.databinding.ActivityMainSplashBinding
import com.greyshark.sanotrive.main.MainActivity
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.DialogButBean
import com.common.app.data.bean.overView.CardSettingListModel
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.dialog.CommonDialog
import com.common.app.helper.RouterHelper
import com.common.app.utls.Constants
import com.common.base.widget.popup.RecyclerPopupWindow
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AllCardTypeConfig
import com.module.user.ui.login.LoginActivity

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：APP启动页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_SPLASH_ACTIVITY)
class SplashActivity : AppActivity<ActivityMainSplashBinding, SplashViewModel>(),
    PrivacyPolicyDialog.OnPrivacyPolicyClickListener, OnClickListener {

    private var privacyPolicyDialog: PrivacyPolicyDialog? = null

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var commonMessageRelayModel: CommonMessageRelayModel? = null

    private var timeCountUtil: TimeCountUtil? = null

    var popList: RecyclerPopupWindow<String>? = null

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true
    override fun getViewModel() = SplashViewModel::class.java
    override fun getViewContentBinding() = ActivityMainSplashBinding.inflate(layoutInflater)

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        privacyPolicyDialog = PrivacyPolicyDialog(this, this)

        doOnNewThread {
//            AizoSDKUtil.initAizoServiceSdk(AizoSDKUtil.getRingFirm())
            AizoSDKUtil.curMac?.let { macIt ->
                AizoSDKUtil.isConnect().no {
                    AizoSDKUtil.connectBleAndInitDevice(macIt, AizoSDKUtil.getRingFirm())
                }
            }
        }

    }

    override fun lazyInitData() {
        super.lazyInitData()

        setVisibility(mViewContentBinding.userSetting, DebugUtils.isEnvShow())

        setText(
            mViewContentBinding.aboutVcodeTv,
            getString(
                R.string.common_vcode_hint,
                VersionUtils.getVerName(AppUtils.getContext()) + "-" + VersionUtils.getVerCode(
                    AppUtils.getContext()
                )
            )
        )

//        doOnNewThread { Utils.getCityList() }

        val hadShowedPrivacyDialog = SpUtilsManagement.getBoolean(KeyPre.KEY_HAD_SHOWED_PRIVACY_DIALOG, false)
        if (!hadShowedPrivacyDialog) {
            privacyPolicyDialog?.show()
            doOnIOThread {
                //首次构造概览UI配置
                val mData = mutableListOf<CardSettingModel>()
                mData.add(
                    CardSettingModel(
                        name = getString(R.string.common_sleep_hint),
                        sortOrder = 1,
                        itemType = AllCardTypeConfig.TYPE_CARD_SLEEP
                    )
                )
                mData.add(
                    CardSettingModel(
                        name = getString(R.string.common_activity_hint),
                        sortOrder = 2,
                        itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY
                    )
                )
                mData.add(
                    CardSettingModel(
                        name = getString(R.string.common_pressure_hint),
                        sortOrder = 3,
                        itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE
                    )
                )
                mData.add(
                    CardSettingModel(
                        name = getString(R.string.common_signs_hint),
                        sortOrder = 4,
                        itemType = AllCardTypeConfig.TYPE_CARD_SIGNS
                    )
                )
                mData.add(
                    CardSettingModel(
                        name = getString(R.string.common_exercise_hint),
                        sortOrder = 5,
                        itemType = AllCardTypeConfig.TYPE_CARD_EXERCISE
                    )
                )
//                mData.add(
//                    CardSettingModel(
//                        name = getString(R.string.common_period_mg_hint),
//                        sortOrder = 6,
//                        itemType = AllCardTypeConfig.TYPE_CARD_PERIOD
//                    )
//                )
                SpUtilsManagement.putParcelable(KeyPre.KEY_OV_CARD_CONFIG, CardSettingListModel(mData))
            }
            return
        }

        preLoadAll()
    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.userSetting.setOnClickListener(onClick = this)
        mViewContentBinding.tvTLogin.setOnClickListener(onClick = this)
    }

    private fun preLoadAll() {//预加载所有需求

        UserHelper.init()

        UserHelper.isLogin().yes {
            setVisibility(mViewContentBinding.tvTLogin,false)
            timeCountUtil?.cancel()
            timeCountUtil = TimeCountUtil(3)
            timeCountUtil?.setListener(object : TimeCountUtil.TimeCountListener {
                override fun onTimeFinish() {
                    jumpToNext()
                }
            })
            timeCountUtil?.start()
        }.otherwise {
            setVisibility(mViewContentBinding.tvTLogin,true)
        }
    }

    private fun jumpToNext() {
//        if (SPUtil.getInt(KeyPre.HAS_SHOW_GUIDE_VERSION, 0) > 0) {
        toMain()
//        } else {
//            showGuide()
//        }
    }

    private fun toMain() {
        val bundle = Bundle()
        bundle.putParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
        if (UserHelper.isLogin()) {
            (SpUtilsManagement.getInt(KeyPre.KEY_DOWN_CLOUD_DATA_PROGRESS, 0) <= 0).yes {
                RouterHelper.navigationPostcard(RouterHub.ROUTER_DOWN_CLOUD_DATA_ACTIVITY)
                    .withParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
                    .navigation()
                setVisibility(mViewContentBinding.tvTLogin,true)
            }.otherwise {
                startActivity<MainActivity>(bundle, true).run {
                    ((Constants.userBean?.height?:0) <=0).yes {
                        RouterHelper.navigation(RouterHub.ROUTER_COM_PER_INFO_ACTIVITY)
                    }
                }
            }
        } else {
            startActivity<LoginActivity>(bundle, true)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        privacyPolicyDialog?.dismiss()
    }

    override fun onPrivacyServiceAgreeClick() {
        LaunchHelper.launchWebActivity(
            SERVICE_AGREEMENT_SERVER
        )
    }

    override fun onPrivacyPolicyExamineClick() {
        LaunchHelper.launchWebActivity(
            PRIVACY_POLICY_SERVER
        )
    }

    override fun onPrivacyPolicyAgreeClick() {
        privacyPolicyDialog?.dismiss()
        //保存显示过的标识
        SpUtilsManagement.putBoolean(KeyPre.KEY_HAD_SHOWED_PRIVACY_DIALOG, true)

        (this.applicationContext as QXApplication).initTotalSDK()

        preLoadAll()
    }

    override fun onPrivacyPolicyExitClick() {
        privacyPolicyDialog?.dismiss()
        AppUtils.exitApp()
    }

    override fun onClick(v: View?) {
        // 防止多次点击
        if (ViewUtils.isFastClick()) return
        when (v) {
            mViewContentBinding.tvTLogin -> {
                UserHelper.isLogin().yes {
                    (SpUtilsManagement.getInt(KeyPre.KEY_DOWN_CLOUD_DATA_PROGRESS, 0) <= 0).yes {
                        RouterHelper.navigationPostcard(RouterHub.ROUTER_DOWN_CLOUD_DATA_ACTIVITY)
                            .withParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
                            .navigation()
                        setVisibility(mViewContentBinding.tvTLogin,true)
                    }.otherwise {
                        val bundle = Bundle()
                        bundle.putParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
                        startActivity<LoginActivity>(bundle, false)
                    }
                }.otherwise {
                    val bundle = Bundle()
                    bundle.putParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel)
                    startActivity<LoginActivity>(bundle, false)
                }
            }

            mViewContentBinding.userSetting -> showDevelopPopupWindow()//切换环境
        }
    }


    //切换开发环境
    private fun showDevelopPopupWindow() {
        val array = arrayListOf("线上", "测试", "开发8086", "开发8087")
        popList = RecyclerPopupWindow(this, array, AppUtils.getColor(com.module.user.R.color.color_080808))
        popList?.setSelectColor(AppUtils.getColor(com.module.user.R.color.colorPrimaryDark))
        popList?.setPosition(DebugUtils.getCurrentEnvModel() - 1)
        popList?.setOnItemClickListener {
            showMsgDialog(it)
            popList?.dismiss()
        }
        popList?.show(this)
    }

    private fun showMsgDialog(type: Int) {
        CommonDialog.newInstance().setTitle("提示").setContent("切换环境APP重启才会生效,是否继续？")
            .setOnCommonDialogListener(object :
                CommonDialog.OnCommonDialogListener {
                override fun onClick(dialog: CommonDialog, position: Int, data: DialogButBean) {
                    if (position > 0) {
                        when (type) {
                            0 -> DebugUtils.setCurrentEnvModel(EnvModel.RELEASE)
                            1 -> DebugUtils.setCurrentEnvModel(EnvModel.TEST)
                            2 -> DebugUtils.setCurrentEnvModel(EnvModel.DEV)
                            3 -> DebugUtils.setCurrentEnvModel(EnvModel.DEV2)
                        }
                        postDelay(200) {
                            LiveEventBus.get("key_logout_app").post(true)
                            restart()
                        }
                    }
                }
            }).show(supportFragmentManager)
    }
}